package com.hxd.otc.module.order.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.ConfirmPaymentDialog;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.PartConfirmPaymentDialog;
import com.hxd.otc.dialog.PhotoDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.my.activity.ChatActivity;
import com.hxd.otc.module.order.adapter.OrderDetailBankAdapter;
import com.hxd.otc.module.order.bean.AllOrderBean;
import com.hxd.otc.module.order.bean.BankInfoPoData;
import com.hxd.otc.module.order.contract.SaleOrderDetailContract;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.module.order.presenter.SaleOrderDetailPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.CountDownUtils;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.FileUtils;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.LubanUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UCropUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yalantis.ucrop.UCrop;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

import static com.hxd.otc.common.enums.ExValidType.GoogleAuth;


/**
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${} 卖出 订单详情页
 */
public class SaleOrderDetailActivity extends PermissionActivity<SaleOrderDetailPresenter> implements SaleOrderDetailContract.View {

    @BindView(R.id.bt_right1)
    TextView btRight1;

    @BindView(R.id.bt_right2)
    TextView btRight2;

    @BindView(R.id.tv_red)
    TextView tvRed;


    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;

    @BindView(R.id.tv_account)
    TextView tvAccount;

    @BindView(R.id.tv_account_unit)
    TextView tvAccountUnit;

    @BindView(R.id.tv_pay_state)
    TextView tvPayState;

    @BindView(R.id.tv_time)
    TextView tvTime;

    @BindView(R.id.tv_price)
    TextView tvPrice;

    @BindView(R.id.tv_number)
    TextView tvNumber;

    @BindView(R.id.ll_pay_infom)
    LinearLayout llPayInfom;

    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    @BindView(R.id.ll_all)
    LinearLayout llAll;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.rc_bank)
    RecyclerView rcBank;

    @BindView(R.id.iv_sliver)
    ImageView ivSliver;

    @BindView(R.id.iv_tag)
    ImageView ivTag;

    @BindView(R.id.tv_other_name)
    TextView tvOtherName;

    @BindView(R.id.ll_bottom_countdown)
    LinearLayout llBottomCountdown;

    @BindView(R.id.bt_common_code)
    TextView btCommonCode;

    @BindView(R.id.bt_fixed_code)
    TextView btFixedCode;

    /**
     * 订单卖出状态
     */
    public static final int SALE_UNPAID = 0;//未付款
    public static final int SALE_PAYED = 1;//已付款
    public static final int SALE_REPRESENTATION = 3;//申诉中
    public static final int SALE_CANCLED = 9;//已取消
    public static final int SALE_FINISHED = 2;//已完成

    public static final int SALE_PAYED_REQUEST = 123;//申诉 requestCode

    public static final int CANCLE_DETAL_SUCCESS = 1;//取消订单操作成功
    public static final int CONFIRM_PAYMENT_SUCCESS = 3;//确认收款操作成功
    public static final int PART_CONFIRM_PAYMENT_SUCCESS = 6;//部分确认收款操作成功
    public static final int WITHDRAW_SUCCESS = 5;//撤回申诉 操作成功

    private static final int PICK_IMAGE_REQUEST_CODE = 100;
    private static final int OPEN_CAMERA_REQUEST_CODE = 101;

    public static String[] EXTERNAL_PERMISSION = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    AllOrderBean.DataBean orderBean;

    MultipleBlocksDialog uNpayDailog;
    MultipleBlocksDialog callDailog;
    MultipleBlocksDialog commonCodeDailog;

    OrderDetailBankAdapter bankAdapter;

    Disposable mDisposable;

    boolean isRefresh;//是否通知去刷新 订单列表的数据
    int statue = -1;//记录订单状态是否改变
    boolean isFrist = true;//
    boolean isRefreshRedMess;//刷新融云消息
    boolean isShowCommonCode;//刷新融云消息


    @Override
    protected int getLayoutId() {
        return R.layout.activity_sale_order_detail;
    }

    @Override
    protected void initView() {
        if (!getIntent().getExtras().containsKey(AllOrderFragment.ORDERINFO)) {
            return;
        }
        orderBean = (AllOrderBean.DataBean) getIntent().getExtras().getSerializable(AllOrderFragment.ORDERINFO);
//        refreshData();
        rcBank.setLayoutManager(new LinearLayoutManager(this));
        bankAdapter = new OrderDetailBankAdapter();
        rcBank.setAdapter(bankAdapter);
        rcBank.setNestedScrollingEnabled(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (llBottomCountdown.getVisibility() == View.VISIBLE) {
                    isShowCommonCode = false;
                }
                mPresenter.doLoadData(orderBean.subOrderId);
            }
        });

        bankAdapter.setLinenster(new OrderDetailBankAdapter.OnItemClickLinenster() {
            @Override
            public void clickName(BankInfoPoData item) {
                if (llBottomCountdown.getVisibility() == View.VISIBLE) {
                    showToast(getString(R.string.choose_receipt_qrcode));
                    return;
                }
                if (item.type == 3) {
                    copyData(item.realName);
                }
            }

            @Override
            public void clickNumber(BankInfoPoData item) {
                if (llBottomCountdown.getVisibility() == View.VISIBLE) {
                    showToast(getString(R.string.choose_receipt_qrcode));
                    return;
                }
                if (item.type == 3) {
                    copyData(item.payNo);
                }
            }

            @Override
            public void clickItem(BankInfoPoData item) {
                if (llBottomCountdown.getVisibility() == View.VISIBLE) {
                    showToast(getString(R.string.choose_receipt_qrcode));
                    return;
                }
                if (item.type != 3) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alipayAddress", item.qrcodeId);
                    bundle.putInt("type", item.type);
                    $startActivity(AlipayQRcodeActivity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void initData() {
        if (getIntent().getExtras().containsKey(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA)) {
            isRefresh = getIntent().getExtras().getBoolean(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA);
        }
        refreshLayout.autoRefresh(0, 10, 1);


    }

    @Override
    public void onSetData(AllOrderBean.DataBean bean) {
        orderBean = bean;

        refreshData();

        if (isFrist) {
            statue = orderBean.status;
            isFrist = false;
            mPresenter.getOrderBankList(orderBean.subOrderId);
            if (orderBean.status == 0 || orderBean.status == 1)
                getRongUnreadCount();
        }

    }

    @Override
    public void refreshView(int type) {//根据不同操作，刷新View
        setResult(RESULT_OK);
        dismissSpinnerDlg();
        switch (type) {
            case CANCLE_DETAL_SUCCESS:
                orderBean.status = 9;
                refreshData();
                break;
            case PART_CONFIRM_PAYMENT_SUCCESS:
            case CONFIRM_PAYMENT_SUCCESS:
                if (mDisposable != null && !mDisposable.isDisposed()) {
                    mDisposable.dispose();
                }
                postSticky(new Event.RefreshOrderRedEvent(statue, true));
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDERINFO, orderBean);
                bundle.putBoolean(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA, true);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
            case WITHDRAW_SUCCESS:
//                mPresenter.doLoadData(orderId);
                break;
        }
    }

    @Override
    public void getOrderBankList(List<BankInfoPoData> bankInfoPoData) {
        bankAdapter.setNewData(bankInfoPoData);
        if (llBottomCountdown.getVisibility() != View.VISIBLE) {
            setCountDown(bankInfoPoData);
        }

    }

    private void setCountDown(List<BankInfoPoData> bankInfoPoData) {
        //无感商，并且是无感支付订单 并且还要判断 是否是微信或者支付宝，银行卡还是原来的流程
        if (UserHelper.isNonInductivePaySilver() && orderBean.isNosenseOrder() && !isShowCommonCode
                && orderBean.status == 0 && orderBean.fixQrcode == 2) {
            isShowCommonCode = true;
            if ((bankInfoPoData != null && bankInfoPoData.size() > 0) && (bankInfoPoData.get(0).type == 1 || bankInfoPoData.get(0).type == 2)) {
                int time = (int) ((int) (orderBean.createDate - System.currentTimeMillis()) / 1000 + orderBean.qrCodeTimeOut);
                LogUtils.e("System.currentTimeMillis() : " + System.currentTimeMillis());
                LogUtils.e("orderBean.createDate : " + orderBean.createDate);
                LogUtils.e("orderBean.qrCodeTimeOut: " + orderBean.qrCodeTimeOut);
                LogUtils.e("time : " + time);
                if (time > 0) {
                    bankAdapter.isQrcodeGone(true);
                    llBottom.setVisibility(View.GONE);
                    llBottomCountdown.setVisibility(View.VISIBLE);
                    fixedAmountinterval(time);
                    commonCodeinterval(time);
                } else {
                    bankAdapter.isQrcodeGone(false);
                    llBottomCountdown.setVisibility(View.GONE);
                    llBottom.setVisibility(View.VISIBLE);
                }
            } else {
                bankAdapter.isQrcodeGone(false);
                llBottomCountdown.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
            }
        }
    }


    @Override
    public void onHideLoading() {
        super.onHideLoading();
        refreshLayout.finishRefresh();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    public void onError(int code) {
        super.onError(code);
        refreshLayout.finishRefresh();
        dismissSpinnerDlg();
    }

    @Override
    protected SaleOrderDetailPresenter createPresenter() {
        return new SaleOrderDetailPresenter(this);
    }

    @Override
    protected void initPermissions() {
        super.initPermissions();
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        LogUtils.e("======" + orderBean.toString());
        llAll.setVisibility(View.VISIBLE);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        titleBar.setTitleText(getString(R.string.sale_aec, orderBean.symbol));
        tvName.setText(orderBean.getAskNickName());
        tvOrderNumber.setText(String.format("#%s", orderBean.subOrderId));
        tvAccount.setText(StringUtil.format8Number(orderBean.totalPrice));
        tvAccountUnit.setText(orderBean.supportCurrencyCode);


        tvNumber.setText(getResources().getString(R.string.number_detail,
                StringUtil.format8Number(orderBean.volume), orderBean.symbol));
        tvPrice.setText(getResources().getString(R.string.price_detail,
                orderBean.price + "",
                orderBean.supportCurrencyCode + "/" + orderBean.symbol));

        if (orderBean.askUserId.equals(orderBean.orderUserId)) {
            ivSliver.setVisibility(View.VISIBLE);
        } else {
            ivSliver.setVisibility(View.GONE);
        }

        //处理付款人信息
        String confirmPaymentName = StringUtil.emptyIfNull(orderBean.getConfirmPaymentName()).trim();
        if (TextUtils.isEmpty(confirmPaymentName)) {
            tvOtherName.setVisibility(View.GONE);
        } else {
            tvOtherName.setVisibility(View.VISIBLE);
            tvOtherName.setText(ResourceUtil.getString(R.string.order_pay_account_info, confirmPaymentName));
        }

        switch (orderBean.status) {
            case SALE_UNPAID://未付款
                ivTag.setVisibility(View.GONE);
                //无感商，并且是无感支付订单 并且还要判断 是否是微信或者支付宝，银行卡还是原来的流程
                if (UserHelper.isNonInductivePaySilver() && orderBean.fixQrcode == 2) {
                    if (!isFrist && !isShowCommonCode) {
                        setCountDown(bankAdapter.getData());
                    }
//                    else {
//                        bankAdapter.isQrcodeGone(false);
//                        llBottomCountdown.setVisibility(View.GONE);
//                        llBottom.setVisibility(View.VISIBLE);
//                    }
                } else {
                    bankAdapter.isQrcodeGone(false);
                    llBottomCountdown.setVisibility(View.GONE);
                    llBottom.setVisibility(View.VISIBLE);
                }

                if (orderBean.isNosenseOrder()) {
                    btRight1.setVisibility(View.VISIBLE);
                    btRight1.setText(getResources().getString(R.string.confirm_receipt));
                } else {
                    btRight1.setVisibility(View.GONE);
                }
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                tvPayState.setText(getResources().getString(R.string.order_un_pay));

                tvTime.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                btRight2.setVisibility(View.GONE);

                tvAccount.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvAccountUnit.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvName.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                ivSliver.setImageResource(R.mipmap.order_trading_v_icon);
                if (orderBean.remainingTime > 0) {
                    tvTime.setVisibility(View.VISIBLE);
                    interval(Integer.parseInt(orderBean.remainingTime + ""));
                }
                break;
            case SALE_PAYED://已付款
                tvTime.setVisibility(View.GONE);
                ivTag.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvPayState.setText(getResources().getString(R.string.order_pay));

                btRight1.setVisibility(View.VISIBLE);
                btRight1.setText(getString(R.string.confirm_receipt));
                btRight1.setBackgroundColor(getResources().getColor(R.color.color_FF5AC792));
                btRight1.setTextColor(getResources().getColor(R.color.colorWhite));

                btRight2.setVisibility(View.VISIBLE);
                btRight2.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                btRight2.setText(getString(R.string.representation));
                btRight2.setBackgroundColor(getResources().getColor(R.color.colorWhite));

                tvAccount.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvAccountUnit.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvName.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                ivSliver.setImageResource(R.mipmap.order_trading_v_icon);
                break;
            case SALE_REPRESENTATION://申诉中
                tvTime.setVisibility(View.GONE);
                ivTag.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                btRight1.setVisibility(View.GONE);
                btRight2.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));

                break;
            case SALE_CANCLED://已取消
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvPayState.setText(getResources().getString(R.string.order_cancle));
                ivTag.setVisibility(View.VISIBLE);
                btRight2.setBackgroundColor(getResources().getColor(R.color.color_FF95A2AC));
                llPayInfom.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                ivSliver.setImageResource(R.mipmap.order_cancle_trading_v_icon);
                break;
            case SALE_FINISHED:
                $setResult();
                if (orderBean != null && statue != orderBean.status)//订单状态发生改变时 通知更新红点
                    postSticky(new Event.RefreshOrderRedEvent(statue, true));
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDERINFO, orderBean);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
        }
    }

    /**
     * 未付款倒计时款操作
     */
    public void interval(int count) {
        CountDownUtils.interval(count, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                tvTime.setText(DateUtil.getTimeMinutesSecond(along));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                //当倒计时完成，则需要请求订单详情接口，刷新数据，取消订单
                mPresenter.doLoadData(orderBean.subOrderId);
            }
        });
    }

    Disposable mCommonCodeDisposable;

    /**
     * 未付款倒计时款操作
     */
    public void commonCodeinterval(int count) {
        CountDownUtils.interval(count, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mCommonCodeDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                btCommonCode.setText(getString(R.string.common_receipt_code, along + "", "s"));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                bankAdapter.isQrcodeGone(false);
                llBottomCountdown.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                showToast(getString(R.string.used_collection_code_hint));
                setNulllCommon();
            }
        });
    }


    Disposable mFixedAmountDisposable;

    /**
     * 未付款倒计时款操作
     */
    public void fixedAmountinterval(int count) {
        CountDownUtils.interval(count, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mFixedAmountDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                btFixedCode.setText(getString(R.string.fixed_amount_payment_code, along + "", "s"));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                bankAdapter.isQrcodeGone(false);
                llBottomCountdown.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                showToast(getString(R.string.used_collection_code_hint));
                setNullFixed();
            }
        });
    }

    @OnClick({R.id.rl_contact, R.id.bt_call, R.id.bt_right2, R.id.bt_right1, R.id.back_tv, R.id.tv_order_number, R.id.bt_common_code, R.id.bt_fixed_code})
    public void onCliekEvent(View view) {
        switch (view.getId()) {
            case R.id.back_tv: //关闭当页面要发送给订单列表去更新数据
                if (orderBean != null && isRefresh)
                    postSticky(new Event.RefreshOrderListEvent(orderBean.status, true));
                finish();
                break;
            case R.id.rl_contact: //联系对方
                isRefreshRedMess = true;
                Bundle bundle = new Bundle();
                bundle.putSerializable(ChatActivity.EXTRA_ORDER_INFO, orderBean);
                RongIM.getInstance().startConversation(this, Conversation.ConversationType.PRIVATE,
                        orderBean.getAskUserId(), orderBean.getAskNickName(), bundle);
                break;
            case R.id.bt_call://打电话
                call();
                break;
            case R.id.bt_right2:// 最右边按钮 的 左边按钮
                btRight2Click();
                break;
            case R.id.bt_right1:// z最右边的按钮
                btRight1Click();
                break;
            case R.id.tv_order_number:// z最右边的按钮
                copyData(orderBean.subOrderId);
                break;
            case R.id.bt_common_code:// 常用二维码
                commonCode();
                break;
            case R.id.bt_fixed_code:// 上传固定金额二维码
                showPhotoDialog();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRefreshRedMess) {
            getRongUnreadCount();
            isRefreshRedMess = false;
        }
    }

    /**
     * 获取融云未读消息数
     */
    private void getRongUnreadCount() {
        RongIMClient.getInstance().getUnreadCount(Conversation.ConversationType.PRIVATE, orderBean.userId, new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                if (integer != null && integer > 0) {
                    tvRed.setVisibility(View.VISIBLE);
                    tvRed.setText(String.valueOf(integer));
                } else {
                    tvRed.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    private void btRight1Click() {
        switch ((orderBean.status)) {
            case SALE_UNPAID://未付款 ：状态---确认收款 按钮
                LogUtils.e("确认收款--=====");
                if (orderBean.isNosenseOrder()) { // 无感确认收款
                    partConfirmClick();
                } else {
                    confirmClick();// 普通OTC 确认收款
                }
                break;
            case SALE_PAYED://已付款 状态---确认收款 按钮
                LogUtils.e("确认收款--=====");
                if (orderBean.isNosenseOrder()) { // 无感确认收款
                    partConfirmClick();
                } else {
                    confirmClick();// 普通OTC 确认收款
                }

                break;
            case SALE_REPRESENTATION://申诉中---没有状态

                break;
        }
        return;
    }

    private void btRight2Click() {
        switch (orderBean.status) {
            case SALE_UNPAID://未付款 ：  //点击
                // 取消交易，则还是代付款状态，但是按钮变成 已提交取消
//                if (orderBean.orderVo.cancelStatus == 0 || orderBean.orderVo.cancelStatus == 3)
                unPayClick();
                break;
            case SALE_PAYED://已付款 ----申诉按钮
                Bundle bundle = new Bundle();
                bundle.putString(AllOrderFragment.ORDER_ID, orderBean.subOrderId);
                $startActivityForResult(ComplainActivity.class, bundle, SALE_PAYED_REQUEST);
                break;
            case SALE_REPRESENTATION://申诉中----是撤回申诉状态，还是联系客服状态
                break;

        }
        return;
    }

    private void copyData(String bankNo) {
        CommonUtil.copyData(bankNo);
        BlocksToast.get().showToast(UIUtils.getContext().getString(R.string.copy_number_hint));
    }

    Uri outImageUri;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == SALE_PAYED_REQUEST) {
            setResult(RESULT_OK);
        }

        //拍照返回结果
        if (requestCode == OPEN_CAMERA_REQUEST_CODE) {
            if (FileUtils.isImageFile(mCameraFile)) {
                UCropUtils.cropImage(mCameraUri, Uri.fromFile(FileUtils.outImageFile(this, FileUtils.CAMERA)), 1, 1
                        , DataUtils.dp2px(this, 400), DataUtils.dp2px(this, 400), this);
//                resultFiles(mCameraFile);
            }
            //裁剪图片返回结果
        } else if (requestCode == UCrop.REQUEST_CROP) {
            outImageUri = UCrop.getOutput(data);
            if (outImageUri != null) {
                resultFiles(new File(outImageUri.getPath()));
            }
            //相册返回
        } else if (requestCode == PICK_IMAGE_REQUEST_CODE) {
            List<String> filePaths = Matisse.obtainPathResult(data);
            if (filePaths != null && filePaths.size() > 0) {
                UCropUtils.cropImage(FileUtils.fileToUri(this
                        , new File(filePaths.get(0))), Uri.fromFile(FileUtils.outImageFile(this, FileUtils.CAMERA)), 1, 1
                        , DataUtils.dp2px(this, 400), DataUtils.dp2px(this, 400), this);
            }
        }
    }

    private void call() {
        if (callDailog == null) {
            callDailog = new MultipleBlocksDialog(this)
                    .setContent(orderBean.askUserMobile)
                    .setTitle(orderBean.getAskNickName())
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.dial), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callDailog.dismiss();
                            CommonUtil.callPhone(SaleOrderDetailActivity.this, orderBean.askUserMobile);
                        }
                    });
        }
        callDailog.show();
    }

    private void commonCode() {
        if (commonCodeDailog == null) {
            commonCodeDailog = new MultipleBlocksDialog(this)
                    .setTitlewithOutPading(getString(R.string.saved_common_receipt_code))
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.sure), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            commonCodeDailog.dismiss();
                            if (bankAdapter.getData().size() > 0) {
                                mPresenter.fixQRcode(bankAdapter.getData().get(0).id, "0", "");
                            }
                            btCommonCode.setEnabled(false);
                            btFixedCode.setEnabled(false);
                        }
                    });
        }
        commonCodeDailog.show();
    }

    /**
     * 未付款操作---取消交易
     */
    private void unPayClick() {
        if (uNpayDailog == null)
            uNpayDailog = new MultipleBlocksDialog(this)
                    .setContent(getString(R.string.order_detail_unpay_dialog_hint))
                    .setTitle(getString(R.string.deal_cancle))
                    .setTvCancle(getString(R.string.let_me_think))
                    .setTvSure(getString(R.string.confirm_cancel), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uNpayDailog.dismiss();
                            showSpinnerDlg("", true);
                            mPresenter.cancleDetal(orderBean.subOrderId, orderBean.isNosenseOrder() ? "1" : "0");
                        }
                    });

        uNpayDailog.show();
    }


    ConfirmPaymentDialog confirmPaymentDialog;

    /**
     * 确认收款操作
     */
    private void confirmClick() {
        if (confirmPaymentDialog == null) {
            confirmPaymentDialog = new ConfirmPaymentDialog(this);
            confirmPaymentDialog
                    .setChecked(false)
                    .setTitleText(R.string.confirm_receipt)
                    .setMessage(R.string.confirm_payment_dialog_message)
                    .setEditHint(GoogleAuth.equals(UserHelper.getExValidType()) ? R.string.confirm_payment_google_hint : R.string.confirm_payment_dialog_et_hint)
                    .setRequire(R.string.confirm_payment_dialog_require)
                    .setUncheckedWarning(getString(R.string.please_check_the_agreement))
                    .setEmptyContentWarning(getString(R.string.content_not_allow_null))
                    .setOnConfirmClickListener(new ConfirmPaymentDialog.OnConfirmClickListener() {
                        @Override
                        public void onConfirm(Dialog dialog, String password) {
                            dialog.dismiss();
                            showSpinnerDlg("", true);
                            mPresenter.confirmPayment(orderBean.subOrderId);
                        }
                    });
        }
        confirmPaymentDialog.show();

    }

    PartConfirmPaymentDialog partConfirmPaymentDialog;

    /**
     * 确认收款操作
     */
    private void partConfirmClick() {
        if (orderBean.partStatus.equals("0")) {
            mPresenter.partConfirmOrder(orderBean.subOrderId, "");
        } else {

            if (partConfirmPaymentDialog == null) {
                partConfirmPaymentDialog = new PartConfirmPaymentDialog(this);
                partConfirmPaymentDialog
                        .setContent(orderBean.supportCurrencyCode, orderBean.orderTotalPrice + "")
                        .setOnConfirmClickListener(new PartConfirmPaymentDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirm(Dialog dialog, String money) {
                                if (Double.parseDouble(money)<=0){
                                    showToast(getString(R.string.money_bigger_than_zero));
                                    return;
                                }
                                dialog.dismiss();
                                showSpinnerDlg("", true);
                                mPresenter.partConfirmOrder(orderBean.subOrderId, money);
                            }
                        });
            }
            partConfirmPaymentDialog.show();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (orderBean != null && isRefresh)
                postSticky(new Event.RefreshOrderListEvent(orderBean.status, true));
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (uNpayDailog != null)
            uNpayDailog.onDestroy();
        uNpayDailog = null;

        if (callDailog != null)
            callDailog.onDestroy();
        callDailog = null;

        if (commonCodeDailog != null)
            commonCodeDailog.onDestroy();
        commonCodeDailog = null;

        if (partConfirmPaymentDialog != null)
            partConfirmPaymentDialog.setOnConfirmClickListener(null);
        partConfirmPaymentDialog = null;

        if (mDisposable != null && !mDisposable.isDisposed())
            mDisposable.dispose();

        setNullFixed();
        setNulllCommon();

    }

    private PhotoDialog mPhotoDialog;
    private File mCameraFile;
    private Uri mCameraUri;

    protected void showPhotoDialog() {
        if (mPhotoDialog == null) {
            mPhotoDialog = new PhotoDialog(this);
        }
        if (!mPhotoDialog.isShowing()) {
            mPhotoDialog.show();
        }
        mPhotoDialog.setOnPhotoDialogItemClickListener(new PhotoDialog.OnPhotoDialogItemClickListener() {
            @Override
            public void onClickCamera(View view) {
                mPhotoDialog.dismiss();
                openCamera();
            }

            @Override
            public void onClickAlbum(View view) {
                mPhotoDialog.dismiss();
                openAlbum(1);
            }

            @Override
            public void onClickFee(View view) {

            }

            @Override
            public void onClickCancel(View view) {
                mPhotoDialog.dismiss();
            }
        });
    }

    protected void openCamera() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                onCamera();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                BlocksToast.get().showToast(R.string.camera_permissions_are_required);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                showForbidPermissionDialog();
            }

            @Override
            public void onLowVersion() {
                onCamera();
            }
        }, Manifest.permission.CAMERA);
    }


    private void onCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            mCameraFile = FileUtils.outImageFile(this, FileUtils.CAMERA);
            mCameraUri = FileUtils.fileToUri(this, mCameraFile, cameraIntent);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri);
            startActivityForResult(cameraIntent, OPEN_CAMERA_REQUEST_CODE);
        }
    }


    protected void openAlbum(int maxImage) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(maxImage)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(PICK_IMAGE_REQUEST_CODE);
    }

    private void resultFiles(@NonNull File file) {
        btFixedCode.setEnabled(false);
        btCommonCode.setEnabled(false);
        LubanUtils lubanUtils = new LubanUtils();
        ArrayList<String> list = new ArrayList<>();
        list.add(file.getAbsolutePath());
        lubanUtils.withRx(this, list, new Consumer<List<File>>() {
            @Override
            public void accept(List<File> files) throws Exception {
                mPresenter.uploadImage(files.get(0));
                showSpinnerDlg(getString(R.string.be_uploading), false);
            }
        });
    }


    @Override
    public void uploadImageSuccess(String imageId) {
        setNulllCommon();
        setNullFixed();
        if (bankAdapter.getData().size() > 0)
            mPresenter.fixQRcode(bankAdapter.getData().get(0).id, "1", imageId);
    }

    @Override
    public void uploadImageFail(String errMessage) {
        bankAdapter.isQrcodeGone(false);
        dismissSpinnerDlg();
        btFixedCode.setEnabled(true);
        btCommonCode.setEnabled(true);
        llBottomCountdown.setVisibility(View.GONE);
        llBottom.setVisibility(View.VISIBLE);
        showToast(getString(R.string.used_collection_code_hint));
        setNulllCommon();
        setNullFixed();
    }

    @Override
    public void fixQRcodeSucced(String errMessage) {
        bankAdapter.isQrcodeGone(false);
        btFixedCode.setEnabled(true);
        btCommonCode.setEnabled(true);
        dismissSpinnerDlg();
        llBottomCountdown.setVisibility(View.GONE);
        llBottom.setVisibility(View.VISIBLE);
        mPresenter.getOrderBankList(orderBean.subOrderId);

    }

    @Override
    public void fixQRcodeFail(String errMessage) {
        bankAdapter.isQrcodeGone(false);
        btFixedCode.setEnabled(true);
        btCommonCode.setEnabled(true);
        dismissSpinnerDlg();
        llBottomCountdown.setVisibility(View.GONE);
        llBottom.setVisibility(View.VISIBLE);
        showToast(getString(R.string.used_collection_code_hint));
        setNulllCommon();
        setNullFixed();
    }


    private void setNulllCommon() {
        if (mCommonCodeDisposable != null && !mCommonCodeDisposable.isDisposed()) {
            mCommonCodeDisposable.dispose();
        }
        mCommonCodeDisposable = null;
    }

    private void setNullFixed() {
        if (mFixedAmountDisposable != null && !mFixedAmountDisposable.isDisposed()) {
            mFixedAmountDisposable.dispose();
        }
        mFixedAmountDisposable = null;
    }
}
